package com.xinzhi.service.impl;

import cn.hutool.core.util.StrUtil;
import com.xinzhi.config.RabbitConfig;
import com.xinzhi.mapper.ReasonMapper;
import com.xinzhi.pojo.Reason;
import com.xinzhi.service.ReasonService;
import com.xinzhi.utils.RedisUtils;
import com.xinzhi.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ReasonServiceImpl implements ReasonService {

    @Autowired
    private ReasonMapper reasonMapper; // 使用private修饰，推荐的做法

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public Result addScore(String poinexe, Integer  extra) {
        String s = (String) redisUtils.get(poinexe);
        if (StrUtil.isNotEmpty(s)){
            return Result.ok("该加分对象已申请过加分");
        }
        // 实现具体的加分逻辑
        if (poinexe == null){
            return Result.error("申请加分对象不能为空");
        }
        if (extra == null || extra <= 0){
            return Result.error("申请加分分数不能为空或小于等于0");
        }
        if (extra > 20){
            return Result.error("申请加分分数不能超过20分");
        }
        Reason seletpoint = reasonMapper.selectpoint(poinexe);
        if(seletpoint != null){
            redisUtils.set(poinexe, seletpoint.getPoinexe());
            return Result.error("已有相同的数据");
        }
        int i = reasonMapper.addScore(poinexe, extra);
        System.out.println(i);
        redisUtils.set(poinexe,extra);
        return Result.ok("加分成功");
    }




        @Override
        public Result updateScore(String poinexe, Integer extra,Integer id) {
            if (StrUtil.isEmpty(poinexe)) {
                return Result.error("申请修改加分对象不能为空");
            }
            if (extra == null || extra <= 0 || extra > 20) {
                return Result.error("修改的分数必须在0到20之间");
            }
            // 检查Redis缓存
            String cachedValue = (String) redisUtils.get(poinexe);
            if (!StrUtil.isEmpty(cachedValue)) {
                // 如果缓存中不存在，查询数据库
               return Result.error("该加分对象不存在");
            }
            Reason selectpoint = reasonMapper.selectpoint(poinexe);
            if (selectpoint != null) {
                return Result.error("该修改加分对象没有做修改");
            }
            // 更新数据库记录
            int updateResult = reasonMapper.updatepoint(poinexe, extra,id);
            if (updateResult > 0) {
                // 更新成功后，刷新Redis缓存
                redisUtils.set(poinexe, extra.toString());
                return Result.ok("修改成功");
            } else {
                return Result.error("修改失败");
            }
        }
    }

